package cn.shengchao.cap.domain.token;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.continew.starter.core.exception.BaseException;

import java.util.concurrent.TimeUnit;

/**
 * @program: examstarapi
 * @description: 高考志愿填报第三方token
 * @author: Xiong weiqiang
 * @create: 2025-05-21 14:33
 */
@Component
public class CapTokenUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final String AUTH_REQ_URL ="/api/v1/Platform/authorization";
    private static final String TOKEN_VALUE_KEY = "cap_token_value";
    /**
     * 获取第三方高考填报志愿的token
     * @return
     */
    public String getToken() {
        String token=null;
        if (stringRedisTemplate.hasKey(TOKEN_VALUE_KEY)) {
            token = stringRedisTemplate.opsForValue().get(TOKEN_VALUE_KEY);
            return token;
        }else {
            token = getTokenValue();
        }
        return token;
    }

    private String getTokenValue(){
        CapProperties capProperties= SpringUtil.getBean(CapProperties.class );
        if (capProperties==null||capProperties.getApiKey()==null){
            throw new BaseException("高考志愿填报服务的配置错误，无法调用");
        }
        String resultStr=HttpUtil.post(capProperties.getServerUrl()+AUTH_REQ_URL, "apiKey=" + capProperties.getApiKey() + "&secretKey=" + capProperties.getSecretKey());
        if (JSONUtil.isTypeJSON(resultStr)){
            JSONObject jsonObject=new JSONObject(resultStr);
            if ("200".equals(jsonObject.getStr("code"))&&"true".equals(jsonObject.getStr("success"))){
                String authToken= jsonObject.getJSONObject("data").getStr("authorization");
                int expireTime= jsonObject.getJSONObject("data").getInt("expires");
                stringRedisTemplate.opsForValue().set(TOKEN_VALUE_KEY,authToken);
                //缓存token，设置过期时间（提前2分钟）
                stringRedisTemplate.expire(TOKEN_VALUE_KEY,expireTime-2, TimeUnit.MINUTES);
                return authToken;
            }else {
                System.out.println("获取高考志愿填报服务token失败非200:"+resultStr);
            }
        }else {
            System.out.println("获取高考志愿填报服务token失败:"+resultStr);
        }
        return null;
    }

}